import Description from '@/components/Description';
import { sysProfileControllerProfile } from '@/services/ess/sysProfile';
import { useIntl, useModel } from '@umijs/max';
import { Flex } from 'antd';
import type { DescriptionsProps } from 'antd/es/descriptions';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import AddModal from './components/AddModal';
import AddPhoto from './components/addPhoto';
import CommIcon from './components/commonIcon';
import Style from './index.less';

const BaseInfo: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [types_operate, handleType] = useState<string>('');
  const [propsid, setpropsid] = useState<string>('');
  const [detailInfo, setdetailInfo] = useState({});
  const intl = useIntl();
  const userNick = () => {
    handleType('userNick');
    handleModalOpen(true);
  };

  const phoneNumber = () => {
    handleModalOpen(true);
    handleType('phoneNumner');
  };

  const changeEmail = () => {
    handleModalOpen(true);
    handleType('changeEmail');
  };

  const changePassWord = () => {
    handleModalOpen(true);
    handleType('changePassWord');
  };

  const handleAddSubmit = async () => {
    try {
      let result = await sysProfileControllerProfile();
      setdetailInfo(result.data);
      const userInfo = await initialState?.fetchUserInfo?.();
      if (userInfo) {
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            ...userInfo,
          }));
        });
      }
    } catch (error) {
      console.log('错误');
    }
  };

  const handleModalOpen_parent = (res: boolean) => {
    handleModalOpen(res);
  };
  const clum_defaults: number = 12;

  const [items, setItems] = useState<DescriptionsProps['items']>([
    {
      key: 'userName',
      label: intl.formatMessage({ id: 'login.accountName' }),
      children: '',
      span: 6,
    },
    {
      key: 'orgName',
      label: intl.formatMessage({
        id: 'systemManagement.organizationalManagementMenu.affiliatedOrganization',
      }),
      children: '',
      span: 6,
    },
    {
      key: 'nickName',
      label: intl.formatMessage({
        id: 'systemManagement.organizationalManagementMenu.userFullName',
      }),
      children: (
        <Flex justify="space-between" style={{ width: '100%' }}>
          <span></span>
          <CommIcon handClick={userNick}></CommIcon>
        </Flex>
      ),
      span: 6,
    },
    {
      key: 'password',
      label: intl.formatMessage({ id: 'login.password' }),
      children: (
        <Flex justify="space-between" style={{ width: '100%' }}>
          <span></span>
          <CommIcon handClick={changePassWord}></CommIcon>
        </Flex>
      ),
      span: 6,
    },
    {
      key: 'email',
      label: intl.formatMessage({ id: 'login.email' }),
      children: (
        <Flex justify="space-between" style={{ width: '100%' }}>
          <span></span>
          <CommIcon handClick={changeEmail}></CommIcon>
        </Flex>
      ),
      span: 6,
    },
    {
      key: 'phone',
      label: intl.formatMessage({ id: 'login.phone' }),
      children: (
        <Flex justify="space-between" style={{ width: '100%' }}>
          <span></span>
          <CommIcon handClick={phoneNumber}></CommIcon>
        </Flex>
      ),
      span: 6,
    },
  ]);

  const getDynamicSpan = (res: any, key: string) => {
    const arrMap = {
      nickName: userNick,
      password: changePassWord,
      email: changeEmail,
      phone: phoneNumber,
    };
    return (
      <Flex justify="space-between" style={{ width: '100%' }} key={key}>
        <span>{res}</span>
        <CommIcon handClick={arrMap[key]}></CommIcon>
      </Flex>
    );
  };

  useEffect(() => {
    const result = [...items].map((item) => {
      let newSpan;
      if (!['userName', 'orgName'].includes(item.key)) {
        newSpan = getDynamicSpan(detailInfo[item.key], item.key);
      } else {
        newSpan = detailInfo[item.key];
      }
      if (newSpan) {
        item.children = newSpan;
      }
      return item;
    });
    setItems(result);
  }, [detailInfo]);

  useEffect(() => {
    sysProfileControllerProfile().then((res) => {
      setdetailInfo(res?.data);
      setpropsid(res?.data?.userId);
    });
  }, []);

  return (
    <div className="global-full-page">
      <div className={Style.content}>
        <div className={Style.personal_wrap}>
          <div className={Style.userinfo_list}>
            <Description items={items} column={clum_defaults} />
          </div>
          <div className={Style.empty}></div>

          <div className={Style.head_image}>
            <AddPhoto imgurl={detailInfo?.avatar} handleAddSubmit={handleAddSubmit}></AddPhoto>
          </div>
        </div>
        <AddModal
          handleAddSubmit={handleAddSubmit}
          createModalOpen_parent={createModalOpen}
          handleModalOpen={handleModalOpen_parent}
          types_operate={types_operate}
          userId={propsid}
        />
      </div>
    </div>
  );
};
export default BaseInfo;
